# 运行前在cmd命令提示符里输入以下命令，安装必要的库：
# pip install requests beautifulsoup4
# pip install Pillow
# pip install requests
# pip install selenium
# pip install Flask

# 运行程序后，在浏览器访问http://localhost:18080/index

from apscheduler.schedulers.background import BackgroundScheduler
import time
from flask import render_template
from flask import Flask, request
import guessCard_fun as gameFun


app = Flask(__name__)
# 调度器在后台线程中运行，不会阻塞当前线程
scheduler = BackgroundScheduler()
fetch_data = None
date_old = None


# 定义路由
@app.route('/get/data', methods=['GET'])
def get_card_data():

    return {'data': gameFun.card_data_refresh(fetch_data, date_old)}


# 页面跳转
@app.route('/')
def guess_card_index():
    page = request.args.get('page')
    user_agent = request.headers.get('User-Agent')
    if page == 'game':
        if any(key in user_agent for key in ['Android', 'iPhone', 'iPad', 'iPod', 'Chrome']):
            return render_template('m_guessCard.html')  # 移动端游戏页面
        else:
            return render_template('guessCard.html')  # web游戏页面
    elif page is None:
        if any(key in user_agent for key in ['Android', 'iPhone', 'iPad', 'iPod']):
            return render_template('m_index.html')  # 移动端登录页面
        else:
            return render_template('index.html')  # web端登录页面
    else:
        if any(key in user_agent for key in ['Android', 'iPhone', 'iPad', 'iPod']):
            return render_template('m_error.html')
        else:
            return render_template('error.html')


# 移动端页面跳转
#@app.route('/mobile')
#def guess_card_index_m():
#    page = request.args.get('page')
#    if page == 'game':
#        return render_template('m_guessCard.html')  # 游戏页面
#    elif page is None:
#        return render_template('m_index.html')  # 把index.html文件读进来，再交给浏览器
#    else:
#        return render_template('m_error.html')  # 把index.html文件读进来，再交给浏览器


# web登录
@app.route('/login', methods=['GET'])
def login():
    user = request.args.get('user')
    pwd = request.args.get('pwd')
    print("web登录")
    return gameFun.user_login(user, pwd)


# 移动端登录
@app.route('/mobile/login', methods=['GET'])
def login_m():
    user = request.args.get('user')
    pwd = request.args.get('pwd')
    print("移动端登录")
    return gameFun.user_login(user, pwd)


@app.route('/game/update/score', methods=['POST'])
def get_rank():
    user = request.form.get('user')  # 玩家名
    inc = request.form.get('inc')  # 本次增量
    if user is not None and inc is not None:
        return gameFun.rank_data(user, inc)
    else:
        print("玩家%s更新积分失败！", user)
        return {}


# 定时任务 每月1号中午12点执行
scheduler.add_job(func=gameFun.clear_score, trigger="cron", day=1, hour=12, minute=0)
# scheduler.add_job(func=gameFun.clear_score, trigger="interval", seconds=3 * 10)
if __name__ == '__main__':
    date_old = time.time()

    # 初始化卡牌数据
    fetch_data = gameFun.fetch_api_data()

    # 建立redis链接
    # redis_server = gameFun.redis_init()

    # 启动任务列表
    scheduler.start()

    app.run(host='0.0.0.0', debug=False, port=18080)  # 不开启调试模式，程序访问端口为18080
